/**
 * 设备判断工具函数 - JavaScript版本
 * 提供设备类型判断、屏幕尺寸检测、设备特性识别等功能
 * 支持直接复制粘贴使用，无需任何依赖
 * 每个函数都是独立的，可以单独复制使用
 */

// 常量定义
const DEVICE_TYPES = {
  PC: 'pc',
  TABLET: 'tablet',
  MOBILE: 'mobile',
  TV: 'tv',
  WATCH: 'watch',
  UNKNOWN: 'unknown'
};

const SCREEN_ORIENTATIONS = {
  PORTRAIT: 'portrait',
  LANDSCAPE: 'landscape'
};

const SCREEN_CATEGORIES = {
  XS: 'xs',    // < 576px
  SM: 'sm',    // 576px - 767px
  MD: 'md',    // 768px - 991px
  LG: 'lg',    // 992px - 1199px
  XL: 'xl',    // 1200px - 1399px
  XXL: 'xxl'   // >= 1400px
};

/**
 * 获取设备类型
 * @returns {string} 设备类型
 */
function getDeviceType() {
  const userAgent = navigator.userAgent.toLowerCase();
  const screenWidth = window.screen.width;
  const screenHeight = window.screen.height;
  
  // 智能手表检测
  if (screenWidth <= 200 && screenHeight <= 200) {
    return DEVICE_TYPES.WATCH;
  }
  
  // 电视检测
  if (screenWidth >= 1920 && screenHeight >= 1080 && 
      (userAgent.includes('tv') || userAgent.includes('smart-tv'))) {
    return DEVICE_TYPES.TV;
  }
  
  // 移动设备检测
  if (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent)) {
    // 平板检测
    if (screenWidth >= 768 && screenHeight >= 1024) {
      return DEVICE_TYPES.TABLET;
    }
    return DEVICE_TYPES.MOBILE;
  }
  
  // 默认PC
  return DEVICE_TYPES.PC;
}

/**
 * 检查是否为移动设备
 * @returns {boolean} 是否为移动设备
 */
function isMobile() {
  return getDeviceType() === DEVICE_TYPES.MOBILE;
}

/**
 * 检查是否为平板设备
 * @returns {boolean} 是否为平板设备
 */
function isTablet() {
  return getDeviceType() === DEVICE_TYPES.TABLET;
}

/**
 * 检查是否为PC设备
 * @returns {boolean} 是否为PC设备
 */
function isPC() {
  return getDeviceType() === DEVICE_TYPES.PC;
}

/**
 * 检查是否为电视设备
 * @returns {boolean} 是否为电视设备
 */
function isTV() {
  return getDeviceType() === DEVICE_TYPES.TV;
}

/**
 * 检查是否为智能手表
 * @returns {boolean} 是否为智能手表
 */
function isWatch() {
  return getDeviceType() === DEVICE_TYPES.WATCH;
}

/**
 * 获取屏幕分类
 * @returns {string} 屏幕分类
 */
function getScreenCategory() {
  const width = window.innerWidth || document.documentElement.clientWidth || window.screen.width;
  
  if (width < 576) return SCREEN_CATEGORIES.XS;
  if (width < 768) return SCREEN_CATEGORIES.SM;
  if (width < 992) return SCREEN_CATEGORIES.MD;
  if (width < 1200) return SCREEN_CATEGORIES.LG;
  if (width < 1400) return SCREEN_CATEGORIES.XL;
  return SCREEN_CATEGORIES.XXL;
}

/**
 * 检查是否为竖屏
 * @returns {boolean} 是否为竖屏
 */
function isPortrait() {
  return window.innerHeight > window.innerWidth;
}

/**
 * 检查是否为横屏
 * @returns {boolean} 是否为横屏
 */
function isLandscape() {
  return window.innerWidth > window.innerHeight;
}

/**
 * 检查是否为触摸设备
 * @returns {boolean} 是否为触摸设备
 */
function isTouch() {
  return 'ontouchstart' in window || 
         navigator.maxTouchPoints > 0 || 
         navigator.msMaxTouchPoints > 0;
}

/**
 * 检查是否为Retina屏幕
 * @returns {boolean} 是否为Retina屏幕
 */
function isRetina() {
  return window.devicePixelRatio > 1;
}

/**
 * 获取设备信息
 * @returns {Object} 设备信息对象
 */
function getDeviceInfo() {
  const type = getDeviceType();
  const screenWidth = window.screen.width;
  const screenHeight = window.screen.height;
  const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
  const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
  
  return {
    type,
    isMobile: isMobile(),
    isTablet: isTablet(),
    isPC: isPC(),
    isTV: isTV(),
    isWatch: isWatch(),
    screenWidth,
    screenHeight,
    viewportWidth,
    viewportHeight,
    orientation: isPortrait() ? SCREEN_ORIENTATIONS.PORTRAIT : SCREEN_ORIENTATIONS.LANDSCAPE,
    pixelRatio: window.devicePixelRatio || 1,
    userAgent: navigator.userAgent,
    platform: navigator.platform,
    isTouchDevice: isTouch(),
    isRetina: isRetina(),
    screenCategory: getScreenCategory()
  };
}

/**
 * 获取屏幕尺寸信息
 * @returns {Object} 屏幕尺寸信息
 */
function getScreenSize() {
  const width = window.innerWidth || document.documentElement.clientWidth || window.screen.width;
  const height = window.innerHeight || document.documentElement.clientHeight || window.screen.height;
  const category = getScreenCategory();
  
  return {
    category,
    width,
    height,
    isSmall: width < 768,
    isMedium: width >= 768 && width < 992,
    isLarge: width >= 992 && width < 1200,
    isExtraLarge: width >= 1200
  };
}

/**
 * 监听屏幕变化
 * @param {Function} callback - 回调函数
 * @returns {Function} 取消监听的函数
 */
function onScreenChange(callback) {
  const handleResize = () => {
    callback(getDeviceInfo());
  };
  
  window.addEventListener('resize', handleResize);
  window.addEventListener('orientationchange', handleResize);
  
  // 返回取消监听的函数
  return () => {
    window.removeEventListener('resize', handleResize);
    window.removeEventListener('orientationchange', handleResize);
  };
}

/**
 * 监听设备类型变化
 * @param {Function} callback - 回调函数
 * @returns {Function} 取消监听的函数
 */
function onDeviceTypeChange(callback) {
  let lastDeviceType = getDeviceType();
  
  const handleChange = () => {
    const currentDeviceType = getDeviceType();
    if (currentDeviceType !== lastDeviceType) {
      lastDeviceType = currentDeviceType;
      callback(currentDeviceType, getDeviceInfo());
    }
  };
  
  window.addEventListener('resize', handleChange);
  window.addEventListener('orientationchange', handleChange);
  
  // 返回取消监听的函数
  return () => {
    window.removeEventListener('resize', handleChange);
    window.removeEventListener('orientationchange', handleChange);
  };
}

/**
 * 监听屏幕方向变化
 * @param {Function} callback - 回调函数
 * @returns {Function} 取消监听的函数
 */
function onOrientationChange(callback) {
  let lastOrientation = isPortrait() ? SCREEN_ORIENTATIONS.PORTRAIT : SCREEN_ORIENTATIONS.LANDSCAPE;
  
  const handleChange = () => {
    const currentOrientation = isPortrait() ? SCREEN_ORIENTATIONS.PORTRAIT : SCREEN_ORIENTATIONS.LANDSCAPE;
    if (currentOrientation !== lastOrientation) {
      lastOrientation = currentOrientation;
      callback(currentOrientation, getDeviceInfo());
    }
  };
  
  window.addEventListener('resize', handleChange);
  window.addEventListener('orientationchange', handleChange);
  
  // 返回取消监听的函数
  return () => {
    window.removeEventListener('resize', handleChange);
    window.removeEventListener('orientationchange', handleChange);
  };
}

/**
 * 检查是否为小屏幕设备
 * @returns {boolean} 是否为小屏幕设备
 */
function isSmallScreen() {
  const width = window.innerWidth || document.documentElement.clientWidth;
  return width < 768;
}

/**
 * 检查是否为中等屏幕设备
 * @returns {boolean} 是否为中等屏幕设备
 */
function isMediumScreen() {
  const width = window.innerWidth || document.documentElement.clientWidth;
  return width >= 768 && width < 992;
}

/**
 * 检查是否为大屏幕设备
 * @returns {boolean} 是否为大屏幕设备
 */
function isLargeScreen() {
  const width = window.innerWidth || document.documentElement.clientWidth;
  return width >= 992;
}

/**
 * 检查是否为超大屏幕设备
 * @returns {boolean} 是否为超大屏幕设备
 */
function isExtraLargeScreen() {
  const width = window.innerWidth || document.documentElement.clientWidth;
  return width >= 1200;
}

/**
 * 获取视口信息
 * @returns {Object} 视口信息
 */
function getViewportInfo() {
  const width = window.innerWidth || document.documentElement.clientWidth;
  const height = window.innerHeight || document.documentElement.clientHeight;
  
  return {
    width,
    height,
    aspectRatio: width / height,
    isPortrait: height > width,
    isLandscape: width > height,
    density: window.devicePixelRatio || 1
  };
}

/**
 * 检查是否支持触摸
 * @returns {boolean} 是否支持触摸
 */
function supportsTouch() {
  return isTouch();
}

/**
 * 检查是否支持多点触控
 * @returns {boolean} 是否支持多点触控
 */
function supportsMultiTouch() {
  return navigator.maxTouchPoints > 1;
}

/**
 * 获取设备像素比
 * @returns {number} 设备像素比
 */
function getPixelRatio() {
  return window.devicePixelRatio || 1;
}

/**
 * 检查是否为高分辨率屏幕
 * @returns {boolean} 是否为高分辨率屏幕
 */
function isHighResolution() {
  return getPixelRatio() > 1;
}

/**
 * 获取屏幕密度
 * @returns {string} 屏幕密度分类
 */
function getScreenDensity() {
  const ratio = getPixelRatio();
  
  if (ratio <= 1) return 'standard';
  if (ratio <= 1.5) return 'high';
  if (ratio <= 2) return 'retina';
  return 'ultra';
}

/**
 * 检查是否为移动端浏览器
 * @returns {boolean} 是否为移动端浏览器
 */
function isMobileBrowser() {
  const userAgent = navigator.userAgent.toLowerCase();
  return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
}

/**
 * 检查是否为桌面端浏览器
 * @returns {boolean} 是否为桌面端浏览器
 */
function isDesktopBrowser() {
  return !isMobileBrowser();
}

/**
 * 获取浏览器信息
 * @returns {Object} 浏览器信息
 */
function getBrowserInfo() {
  const userAgent = navigator.userAgent;
  
  return {
    userAgent,
    platform: navigator.platform,
    language: navigator.language,
    cookieEnabled: navigator.cookieEnabled,
    onLine: navigator.onLine,
    isMobile: isMobileBrowser(),
    isDesktop: isDesktopBrowser()
  };
}

/**
 * 检查是否支持特定功能
 * @param {string} feature - 功能名称
 * @returns {boolean} 是否支持
 */
function supportsFeature(feature) {
  switch (feature) {
    case 'touch':
      return isTouch();
    case 'retina':
      return isRetina();
    case 'multitouch':
      return supportsMultiTouch();
    case 'orientation':
      return 'orientation' in window;
    case 'fullscreen':
      return !!(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled);
    case 'geolocation':
      return 'geolocation' in navigator;
    case 'camera':
      return 'mediaDevices' in navigator && 'getUserMedia' in navigator.mediaDevices;
    case 'vibration':
      return 'vibrate' in navigator;
    default:
      return false;
  }
}

/**
 * 获取设备能力信息
 * @returns {Object} 设备能力信息
 */
function getDeviceCapabilities() {
  return {
    touch: isTouch(),
    multitouch: supportsMultiTouch(),
    retina: isRetina(),
    orientation: 'orientation' in window,
    fullscreen: !!(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled),
    geolocation: 'geolocation' in navigator,
    camera: 'mediaDevices' in navigator && 'getUserMedia' in navigator.mediaDevices,
    vibration: 'vibrate' in navigator,
    webgl: !!window.WebGLRenderingContext,
    webgl2: !!window.WebGL2RenderingContext,
    serviceWorker: 'serviceWorker' in navigator,
    pushNotification: 'PushManager' in window
  };
}

/**
 * 检查是否为特定设备
 * @param {string} deviceType - 设备类型
 * @returns {boolean} 是否为指定设备
 */
function isDevice(deviceType) {
  return getDeviceType() === deviceType;
}

/**
 * 检查屏幕尺寸是否在指定范围内
 * @param {number} minWidth - 最小宽度
 * @param {number} maxWidth - 最大宽度
 * @returns {boolean} 是否在范围内
 */
function isScreenSizeInRange(minWidth, maxWidth) {
  const width = window.innerWidth || document.documentElement.clientWidth;
  return width >= minWidth && width <= maxWidth;
}

/**
 * 获取响应式断点
 * @returns {string} 当前断点
 */
function getResponsiveBreakpoint() {
  const width = window.innerWidth || document.documentElement.clientWidth;
  
  if (width < 576) return 'xs';
  if (width < 768) return 'sm';
  if (width < 992) return 'md';
  if (width < 1200) return 'lg';
  if (width < 1400) return 'xl';
  return 'xxl';
}

/**
 * 检查是否匹配媒体查询
 * @param {string} mediaQuery - 媒体查询字符串
 * @returns {boolean} 是否匹配
 */
function matchesMediaQuery(mediaQuery) {
  return window.matchMedia(mediaQuery).matches;
}

/**
 * 监听媒体查询变化
 * @param {string} mediaQuery - 媒体查询字符串
 * @param {Function} callback - 回调函数
 * @returns {Function} 取消监听的函数
 */
function onMediaQueryChange(mediaQuery, callback) {
  const mediaQueryList = window.matchMedia(mediaQuery);
  
  const handleChange = (e) => {
    callback(e.matches, mediaQueryList);
  };
  
  // 现代浏览器
  if (mediaQueryList.addEventListener) {
    mediaQueryList.addEventListener('change', handleChange);
    return () => mediaQueryList.removeEventListener('change', handleChange);
  }
  // 旧版浏览器
  else if (mediaQueryList.addListener) {
    mediaQueryList.addListener(handleChange);
    return () => mediaQueryList.removeListener(handleChange);
  }
  
  return () => {};
}

/**
 * 获取所有设备信息
 * @returns {Object} 完整的设备信息
 */
function getAllDeviceInfo() {
  return {
    device: getDeviceInfo(),
    screen: getScreenSize(),
    viewport: getViewportInfo(),
    browser: getBrowserInfo(),
    capabilities: getDeviceCapabilities(),
    responsive: {
      breakpoint: getResponsiveBreakpoint(),
      category: getScreenCategory()
    }
  };
}

// 支持多种导出方式
if (typeof module !== 'undefined' && module.exports) {
  // Node.js 环境
  module.exports = {
    // 函数式导出
    getDeviceType,
    isMobile,
    isTablet,
    isPC,
    isTV,
    isWatch,
    getScreenCategory,
    isPortrait,
    isLandscape,
    isTouch,
    isRetina,
    getDeviceInfo,
    getScreenSize,
    onScreenChange,
    onDeviceTypeChange,
    onOrientationChange,
    isSmallScreen,
    isMediumScreen,
    isLargeScreen,
    isExtraLargeScreen,
    getViewportInfo,
    supportsTouch,
    supportsMultiTouch,
    getPixelRatio,
    isHighResolution,
    getScreenDensity,
    isMobileBrowser,
    isDesktopBrowser,
    getBrowserInfo,
    supportsFeature,
    getDeviceCapabilities,
    isDevice,
    isScreenSizeInRange,
    getResponsiveBreakpoint,
    matchesMediaQuery,
    onMediaQueryChange,
    getAllDeviceInfo,
    // 常量导出
    DEVICE_TYPES,
    SCREEN_ORIENTATIONS,
    SCREEN_CATEGORIES
  };
} else if (typeof window !== 'undefined') {
  // 浏览器环境
  window.getDeviceType = getDeviceType;
  window.isMobile = isMobile;
  window.isTablet = isTablet;
  window.isPC = isPC;
  window.isTV = isTV;
  window.isWatch = isWatch;
  window.getScreenCategory = getScreenCategory;
  window.isPortrait = isPortrait;
  window.isLandscape = isLandscape;
  window.isTouch = isTouch;
  window.isRetina = isRetina;
  window.getDeviceInfo = getDeviceInfo;
  window.getScreenSize = getScreenSize;
  window.onScreenChange = onScreenChange;
  window.onDeviceTypeChange = onDeviceTypeChange;
  window.onOrientationChange = onOrientationChange;
  window.isSmallScreen = isSmallScreen;
  window.isMediumScreen = isMediumScreen;
  window.isLargeScreen = isLargeScreen;
  window.isExtraLargeScreen = isExtraLargeScreen;
  window.getViewportInfo = getViewportInfo;
  window.supportsTouch = supportsTouch;
  window.supportsMultiTouch = supportsMultiTouch;
  window.getPixelRatio = getPixelRatio;
  window.isHighResolution = isHighResolution;
  window.getScreenDensity = getScreenDensity;
  window.isMobileBrowser = isMobileBrowser;
  window.isDesktopBrowser = isDesktopBrowser;
  window.getBrowserInfo = getBrowserInfo;
  window.supportsFeature = supportsFeature;
  window.getDeviceCapabilities = getDeviceCapabilities;
  window.isDevice = isDevice;
  window.isScreenSizeInRange = isScreenSizeInRange;
  window.getResponsiveBreakpoint = getResponsiveBreakpoint;
  window.matchesMediaQuery = matchesMediaQuery;
  window.onMediaQueryChange = onMediaQueryChange;
  window.getAllDeviceInfo = getAllDeviceInfo;
  window.DEVICE_TYPES = DEVICE_TYPES;
  window.SCREEN_ORIENTATIONS = SCREEN_ORIENTATIONS;
  window.SCREEN_CATEGORIES = SCREEN_CATEGORIES;
}